<template>
  <div>
    <!-- 顶部的面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-s-promotion"></i> 后台管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/admin/mall' }">商城管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/admin/mall/goods' }">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>发布商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 表单 -->
    <el-divider content-position="left"></el-divider>
    <div class="rule-form">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
        <el-form-item label="类别" prop="categoryId">
          <el-cascader
              style="width: 100%;"
              placeholder="请选择商品类别"
              v-model="ruleForm.categoryId"
              :options="categoryOptions"></el-cascader>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="封面图" prop="coverUrl">
          <div class="picture-preview" v-if="ruleForm.coverUrl">
            <el-image class="image"
                      :src="ruleForm.coverUrl"
                      fit="cover"></el-image>
          </div>
          <el-upload
              class="picture-uploader"
              :show-file-list="false"
              :action="BaseUrl.ATTACHMENT + '/upload/image/goods'"
              :on-success="handleUploadSuccess"
              :headers="uploadHeaders">
            <i class="el-icon-upload picture-uploader-icon"></i>
            <div v-if="ruleForm.coverUrl" class="picture-uploader-text"><i>点击重新上传</i></div>
            <div class="picture-uploader-text">仅允许上传 <i>JPG</i> / <i>PNG</i> 格式的图片</div>
            <div class="picture-uploader-text">仅允许上传不超过 <i>5MB</i> 的图片</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="brief">
          <el-input v-model="ruleForm.brief"></el-input>
        </el-form-item>
        <el-form-item label="条码" prop="barCode">
          <el-input v-model="ruleForm.barCode"></el-input>
        </el-form-item>
        <el-form-item label="关键词列表" prop="keywords">
          <el-input v-model="ruleForm.keywords"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="salePrice">
          <el-input v-model="ruleForm.salePrice"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="ruleForm.sort"></el-input>
        </el-form-item>
        <el-form-item label="商品详情" prop="detail">
          <div id="wangEditor"></div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
          <el-button type="warning" @click="gotoList()">返回列表</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 上传组件需要使用的请求头
      uploadHeaders: {
        Authorization: JSON.parse(localStorage.getItem('loginInfo')).token
      },
      // 类别下拉列表选项
      categoryOptions: [],
      // 表单
      ruleForm: {
        categoryId: '',
        coverUrl: '',
        title: '2023年明前特级信阳毛尖绿茶 250克（125g*2罐）',
        brief: '细、圆、紧、直 鲜爽持久',
        barCode: '11010100111010',
        salePrice: 256,
        keywords: '关键词1,关键词2,关键词3',
        sort: 99,
        detail: ''
      },
      // 表单验证规则
      rules: {
        categoryId: [
          {required: true, message: '请输入类别ID', trigger: 'blur'},
          {pattern: /^\d+$/, message: '请选择有效的类别', trigger: 'blur'}
        ],
        coverUrl: [
          {required: true, message: '请上传封面图', trigger: 'blur'}
        ],
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 2, max: 255, message: '标题的长度必须是 2 到 255 个字符', trigger: 'blur'}
        ],
        brief: [
          {required: true, message: '请输入简介', trigger: 'blur'},
          {min: 2, max: 255, message: '简介的长度必须是 2 到 255 个字符', trigger: 'blur'}
        ],
        barCode: [
          {required: true, message: '请输入条码', trigger: 'blur'},
          {min: 10, max: 50, message: '条码的长度必须是 10 到 50 个字符', trigger: 'blur'}
        ],
        keywords: [
          {required: true, message: '请输入类别关键词列表', trigger: 'blur'},
          {min: 2, max: 35, message: '长度在 2 到 35 个字符', trigger: 'blur'}
        ],
        salePrice: [
          {required: true, message: '请输入售价', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '请输入排序序号', trigger: 'blur'},
          {pattern: /^(\d{1}|[1-9]{1}[0-9]?)$/, message: '排序序号必须是 0~99 之间的数字', trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    // 返回列表
    gotoList() {
      this.$router.push('./');
    },
    // 初始化富文本编辑器
    initWangEditor() {
      this.editor = new this.wangEditor('#wangEditor');
      this.editor.config.uploadImgServer = this.BaseUrl.ATTACHMENT + '/upload/image/goods';
      this.editor.config.uploadFileName = 'file';
      this.editor.config.uploadImgHooks = {
        customInsert: function (insertImgFn, result) {
          insertImgFn(result.data.url);
        }
      };
      this.editor.config.uploadImgHeaders = {
        'Authorization': JSON.parse(localStorage.getItem('loginInfo')).token
      };
      this.editor.config.zIndex = 1;
      this.editor.create();
    },
    // 上传成功后的回调
    handleUploadSuccess(response) {
      console.log(response)
      if (response.state == 20000) {
        this.ruleForm.coverUrl = response.data.url;
      } else {
        let title = '操作失败';
        this.$alert(response.message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      }
    },
    // 提交表单
    submitForm(formName) {
      if (Array.isArray(this.ruleForm.categoryId)) {
        this.ruleForm.categoryId = this.ruleForm.categoryId.pop();
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.detail = this.editor.txt.html();

          let url = this.BaseUrl.ADMIN_MALL + '/goods/add-new';
          console.log('url = ' + url);

          this.TokenAxios.post(url, this.ruleForm).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state == 20000) {
              this.$message({
                message: '发布商品成功！（为了便于测试时连接多次发布商品，发布成功后不会重置表单）',
                type: 'success'
              });
              this.resetForm(formName);
            } else {
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          }).catch(error => {
            let title = '错误';
            let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
            this.$alert(message, title, {
              confirmButtonText: '确定',
              callback: action => {
              }
            });
            console.log(error);
          });
        } else {
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 加载类别树的数据
    loadCategoryTree() {
      let url = this.BaseUrl.ADMIN_MALL + '/categories/tree';
      console.log('url = ' + url);

      this.TokenAxios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.categoryOptions = jsonResult.data;
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
  },
  mounted() {
    this.initWangEditor();
    this.loadCategoryTree();
  }
}
</script>

<style>
.picture-uploader {
  float: left;
  width: 240px;
  height: 135px;
  margin-right: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.picture-uploader .picture-uploader-icon {
  width: 240px;
  height: 80px;
  font-size: 58px;
  color: #8c939d;
  line-height: 80px;
  text-align: center;
}

.picture-uploader .picture-uploader-text {
  width: 240px;
  height: 18px;
  line-height: 18px;
  text-align: center;
  font-size: 10px;
  color: #8c939d;
}

.picture-uploader .picture-uploader-text i {
  font-size: 10px;
  font-weight: bold;
  font-style: normal;
  color: #F56C6C;
}

.picture-preview {
  width: 240px;
  height: 135px;
  margin-right: 20px;
  border: 1px solid #e8e6e6;
  border-radius: 6px;
  float: left;
  display: inline;
  position: relative;
}

.picture-preview .image {
  width: 240px;
  height: 135px;
  border-radius: 6px;
}
</style>